package com.justech.eat.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @program: eat-service
 * @description: hr数据库配置
 * @author: feifei.li
 * @create: 2020-06-17 16:32
 **/
@Configuration
@MapperScan(basePackages = "com.justech.eat.mapper.hr", sqlSessionFactoryRef = "hrSqlSessionFactory")
public class MyBatisHrConfig {

    @Bean(name = "hrDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.hr")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "hrTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("hrDataSource") DataSource datasource) {
        return new DataSourceTransactionManager(datasource);
    }

    @Bean(name = "hrSqlSessionFactory")
    public SqlSessionFactory basicSqlSessionFactory(@Qualifier("hrDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:hr/*.xml")
        );
        return factoryBean.getObject();
    }

    @Bean(name = "hrSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("hrSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
